﻿
using Cms.Core.Infrastructure.Common;
using Cms.Core.Infrastructure.Dependency;
using Cms.Core.Infrastructure.Helps;
using Cms.Core.Infrastructure.Log;
using Cms.Core.Infrastructure.Ui;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Cms.Core.AspNetMvc.Mvc.Filter
{
    /// <summary>
    /// 异步自定义错误过程器
    /// </summary>
    public class AsyncGlobalExceptionsFilter : IAsyncExceptionFilter
    {
        public async Task OnExceptionAsync(ExceptionContext context)
        {

            var controller = context.ActionDescriptor;

            context.ExceptionHandled = true;
            var exp = context.Exception;
            var message = exp.Message;
            var log = ServiceLocator.Instance.GetService<ILoggerHelper>();
            log.Error(controller,exp);
            //context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            if (context.HttpContext.Request.IsJsonContextType())
            {
                AjaxResult result = new AjaxResult();
                result.Success =false;
                result.Type = AjaxResultType.Error;
                result.Message = "内部错误!!";
                await context.HttpContext.Response.WriteAsync(result.ToJson());
            }
            else
            {
                context.HttpContext.Response.ContentType = "text/html;charset=utf-8";
                await context.HttpContext.Response.WriteAsync($"服务器错误，错误信息{message}");
            }
        }
    }
}
